import { defineStore } from 'pinia'
import { login, register, updateUserInfo, updatePassword } from '../api/user'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo') || 'null')
  }),
  
  getters: {
    isLoggedIn: (state) => !!state.token,
    username: (state) => state.userInfo?.username
  },
  
  actions: {
    async login(loginData) {
      try {
        const response = await login(loginData)
        const { token, user } = response.data.data
        
        // 保存token和用户信息
        this.token = token
        this.userInfo = user
        localStorage.setItem('token', token)
        localStorage.setItem('userInfo', JSON.stringify(user))
        
        return response
      } catch (error) {
        console.error('Login error:', error.response?.data || error)
        throw error.response?.data || error
      }
    },
    
    async register(registerData) {
      try {
        const response = await register(registerData)
        return response
      } catch (error) {
        console.error('Register error:', error)
        throw error
      }
    },
    
    logout() {
      this.token = ''
      this.userInfo = null
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    },
    
    async updateUserInfo(data) {
      try {
        const response = await updateUserInfo(this.userInfo.id, data)
        if (response.data && response.data.data) {
          this.userInfo = response.data.data
        }
        return response
      } catch (error) {
        console.error('Update user info error:', error)
        throw error
      }
    },
    
    async updatePassword(data) {
      try {
        const response = await updatePassword(this.userInfo.id, data)
        return response
      } catch (error) {
        console.error('Update password error:', error.response?.data || error)
        throw error.response?.data || error
      }
    }
  }
}) 